<template>
  <div class="fun-fact-list">
    <el-card>
      <!-- 页面标题和操作按钮 -->
      <div class="page-header">
        <div class="header-left">
          <h2>冷知识管理</h2>
          <p class="description">管理音乐节相关的趣味冷知识内容</p>
        </div>
        <div class="header-right">
          <el-button 
            v-if="userStore.hasPermission(ALL_PERMISSIONS.CONTENT_CREATE)"
            type="primary" 
            @click="showCreateDialog"
          >
            <el-icon><Plus /></el-icon>
            添加冷知识
          </el-button>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.search"
              placeholder="搜索标题、内容等"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.isActive" placeholder="选择状态" clearable>
              <el-option label="启用" :value="true" />
              <el-option label="禁用" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 冷知识列表 -->
      <el-table
        v-loading="loading"
        :data="funFactList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200" />
        <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'danger'">
              {{ row.isActive ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="userStore.hasPermission(ALL_PERMISSIONS.CONTENT_READ)"
              size="small" 
              @click="viewFunFact(row)"
            >
              查看
            </el-button>
            <el-button 
              v-if="userStore.hasPermission(ALL_PERMISSIONS.CONTENT_UPDATE)"
              size="small" 
              type="primary" 
              @click="editFunFact(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="userStore.hasPermission(ALL_PERMISSIONS.CONTENT_DELETE)"
              size="small" 
              type="danger" 
              @click="deleteFunFact(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
                  :current-page="pagination.page"
        :page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="formData.title"
            placeholder="请输入冷知识标题"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="4"
            placeholder="请输入冷知识内容"
            maxlength="60"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="关联艺人" prop="artistId">
          <el-select v-model="formData.artistId" placeholder="选择关联艺人" clearable>
            <el-option
              v-for="artist in artistList"
              :key="artist.id"
              :label="artist.name"
              :value="artist.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
                  <el-radio-group v-model="formData.isActive">
          <el-radio :value="true">启用</el-radio>
          <el-radio :value="false">禁用</el-radio>
        </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { contentApi } from '@/api'
import { artistApi } from '@/api'
import { useUserStore } from '@/stores/user'
import { ALL_PERMISSIONS } from '@/constants/permissions'
import { formatDate } from '@/utils/format'
import type { FunFact } from '@/types'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const funFactList = ref<FunFact[]>([])
const artistList = ref<any[]>([]) // Changed from Artist[] to any[] as Artist type is removed
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

const searchForm = reactive({
  search: '',
  isActive: null as boolean | null
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const currentId = ref<number | null>(null)
const submitLoading = ref(false)
const formRef = ref()

const formData = reactive({
  title: '',
  content: '',
  artistId: null as number | null,
  isActive: true
})

const formRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 10, max: 500, message: '内容长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 获取冷知识列表
const fetchFunFacts = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      ...searchForm
    }
    const response = await contentApi.funFacts.getList(params)
    funFactList.value = response.data.data
    pagination.total = response.data.pagination.total
    pagination.page = response.data.pagination.page
    pagination.limit = response.data.pagination.limit
  } catch (error) {
    ElMessage.error('获取冷知识列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchFunFacts()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    search: '',
    isActive: null
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  fetchFunFacts()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchFunFacts()
}

// 获取艺人列表
const fetchArtists = async () => {
  try {
    const response = await artistApi.getList({ limit: 1000 })
    artistList.value = response.data.data
  } catch (error) {
    ElMessage.error('获取艺人列表失败')
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  dialogVisible.value = true
  dialogTitle.value = '创建冷知识'
  isEdit.value = false
  currentId.value = null
  formData.title = ''
  formData.content = ''
  formData.artistId = null
  formData.isActive = true
}

// 编辑冷知识
const editFunFact = (funFact: FunFact) => {
  dialogVisible.value = true
  dialogTitle.value = '编辑冷知识'
  isEdit.value = true
  currentId.value = funFact.id
  formData.title = funFact.title
  formData.content = funFact.content
  formData.artistId = funFact.artistId
  formData.isActive = funFact.isActive
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value && currentId.value) {
      await contentApi.funFacts.update(currentId.value, formData)
      ElMessage.success('更新成功')
    } else {
      await contentApi.funFacts.create(formData)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchFunFacts()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    submitLoading.value = false
  }
}

// 查看冷知识详情
const viewFunFact = async (funFact: FunFact) => {
  try {
    const response = await contentApi.funFacts.getById(funFact.id)
    const detailFunFact = response.data.funFact
    
    ElMessageBox.alert(
      `
      <div style="text-align: left;">
        <h3>${detailFunFact.title}</h3>
        <p><strong>内容：</strong>${detailFunFact.content}</p>
        <p><strong>关联艺人：</strong>${detailFunFact.artist?.name || '无'}</p>
        <p><strong>状态：</strong>${detailFunFact.isActive ? '启用' : '禁用'}</p>
        <p><strong>创建时间：</strong>${formatDate(detailFunFact.createdAt)}</p>
      </div>
      `,
      '冷知识详情',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定'
      }
    )
  } catch (error) {
    ElMessage.error('获取冷知识详情失败')
  }
}

// 删除冷知识
const deleteFunFact = async (funFact: FunFact) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除冷知识 "${funFact.title}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await contentApi.funFacts.delete(funFact.id)
    ElMessage.success('删除成功')
    fetchFunFacts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 初始化
onMounted(() => {
  fetchFunFacts()
  fetchArtists()
})
</script>

<style scoped>
.fun-fact-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}
</style> 